<template>
  <div class="app-container">
    <!-- ========== 上半部分：采购记录管理 ========== -->
    <el-card class="purchase-records-section" shadow="never">
      <div slot="header" class="card-header">
        <span class="card-title">采购记录管理</span>
      </div>

      <!-- 查询表单 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="SKU编码" prop="sku">
          <el-input
            v-model="queryParams.sku"
            placeholder="请输入SKU编码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="所属店铺" prop="shopId">
          <el-select v-model="queryParams.shopId" placeholder="请选择店铺" clearable>
            <el-option
              v-for="item in shopOptions"
              :key="item.shopId"
              :label="item.shopName"
              :value="item.shopId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="采购日期">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['purchase:manage:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['purchase:manage:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['purchase:manage:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['purchase:manage:export']"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['purchase:inbound:import']"
          >导入</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="mb8 stat-cards">
        <el-col :span="6">
          <el-card shadow="hover" :body-style="{ padding: '15px' }">
            <div class="stat-card">
              <div class="stat-icon" style="background: #409EFF;">
                <i class="el-icon-goods"></i>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ totalAmount }}</div>
                <div class="stat-label">总计采购金额</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" :body-style="{ padding: '15px' }">
            <div class="stat-card">
              <div class="stat-icon" style="background: #67C23A;">
                <i class="el-icon-shopping-cart-2"></i>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ totalQuantity }}</div>
                <div class="stat-label">总计采购数量</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" :body-style="{ padding: '15px' }">
            <div class="stat-card">
              <div class="stat-icon" style="background: #E6A23C;">
                <i class="el-icon-box"></i>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ totalRecords }}</div>
                <div class="stat-label">采购记录数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" :body-style="{ padding: '15px' }">
            <div class="stat-card">
              <div class="stat-icon" style="background: #F56C6C;">
                <i class="el-icon-money"></i>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ avgUnitPrice }}</div>
                <div class="stat-label">平均单价</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="purchaseList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="SKU编码" align="center" prop="sku" width="150" :show-overflow-tooltip="true" />
        <el-table-column label="SKU货号" align="center" prop="skuCode" width="120" :show-overflow-tooltip="true" />
        <el-table-column label="产品名称" align="center" prop="productName" width="150" :show-overflow-tooltip="true" />
        <el-table-column label="SKU属性" align="center" prop="skuAttr" width="150" :show-overflow-tooltip="true" />
        <el-table-column label="所属店铺" align="center" prop="shopName" width="120" />
        <el-table-column label="采购数量" align="center" prop="purchaseQuantity" width="100" />
        <el-table-column label="采购金额" align="center" prop="purchaseAmount" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.purchaseAmount ? '¥' + scope.row.purchaseAmount : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单品包装费" align="center" prop="packageFee" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.packageFee ? '¥' + scope.row.packageFee : '¥0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品单价" align="center" prop="unitPrice" width="120">
          <template slot-scope="scope">
            <span style="color: #67C23A; font-weight: bold;">{{ scope.row.unitPrice ? '¥' + scope.row.unitPrice : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="采购日期" align="center" prop="purchaseDate" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.purchaseDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['purchase:manage:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['purchase:manage:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="500px" append-to-body center>
      <div>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-error="handleFileError"
          :auto-upload="false"
          drag
          style="text-align: center;"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据
            </div>
            <span style="color: #E6A23C;">
              <i class="el-icon-warning"></i> 
              Excel中必须包含"所属店铺"列，店铺不存在会自动创建
            </span>
            <br/>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading" :disabled="upload.isUploading">
          {{ upload.isUploading ? '导入中...' : '确 定' }}
        </el-button>
        <el-button @click="upload.open = false" :disabled="upload.isUploading">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改采购记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="SKU编码" prop="sku">
              <el-select v-model="form.sku" placeholder="请选择SKU" filterable style="width: 100%" @change="handleSkuChange">
                <el-option
                  v-for="item in productOptions"
                  :key="item.sku"
                  :label="item.sku + ' - ' + item.productName"
                  :value="item.sku"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="选择SKU后自动填充" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="SKU货号" prop="skuCode">
              <el-input v-model="form.skuCode" placeholder="选择SKU后自动填充" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属店铺" prop="shopId">
              <el-select v-model="form.shopId" placeholder="选择SKU后自动填充" style="width: 100%" disabled>
                <el-option
                  v-for="item in shopOptions"
                  :key="item.shopId"
                  :label="item.shopName"
                  :value="item.shopId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购数量" prop="purchaseQuantity">
              <el-input-number v-model="form.purchaseQuantity" :min="1" :max="999999" placeholder="请输入采购数量" style="width: 100%" @change="calculateUnitPrice" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购金额" prop="purchaseAmount">
              <el-input-number v-model="form.purchaseAmount" :precision="2" :min="0" :max="9999999" placeholder="请输入采购金额" style="width: 100%" @change="calculateUnitPrice" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单品包装费" prop="packageFee">
              <el-input-number v-model="form.packageFee" :precision="2" :min="0" :max="999" placeholder="请输入单品包装费" style="width: 100%" @change="calculateUnitPrice" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品单价">
              <el-input v-model="unitPriceDisplay" placeholder="自动计算" disabled style="width: 100%">
                <template slot="prepend">¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="采购日期" prop="purchaseDate">
              <el-date-picker
                v-model="form.purchaseDate"
                type="datetime"
                placeholder="选择采购日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPurchase, getPurchase, delPurchase, addPurchase, updatePurchase, importData, importTemplate } from "@/api/business/purchase"
import { listProduct } from "@/api/business/product"
import { getShopList } from "@/api/system/user"
import { getToken } from "@/utils/auth"

export default {
  name: "PurchaseManage",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购记录表格数据
      purchaseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 店铺选项
      shopOptions: [],
      // 产品选项
      productOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sku: null,
        productName: null,
        shopId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sku: [
          { required: true, message: "SKU编码不能为空", trigger: "change" }
        ],
        // shopId从产品中自动获取，无需用户填写，不需要校验
        purchaseQuantity: [
          { required: true, message: "采购数量不能为空", trigger: "blur" }
        ],
        purchaseAmount: [
          { required: true, message: "采购金额不能为空", trigger: "blur" }
        ],
        purchaseDate: [
          { required: true, message: "采购日期不能为空", trigger: "change" }
        ]
      },
      // 统计数据
      totalAmount: '¥0.00',
      totalQuantity: 0,
      totalRecords: 0,
      avgUnitPrice: '¥0.00',
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/purchase/importData"
      }
    }
  },
  computed: {
    // 计算并显示产品单价
    unitPriceDisplay() {
      if (this.form.purchaseAmount && this.form.purchaseQuantity && this.form.purchaseQuantity > 0) {
        const avgPrice = this.form.purchaseAmount / this.form.purchaseQuantity
        const packageFee = this.form.packageFee || 0
        const unitPrice = (avgPrice + packageFee).toFixed(2)
        return unitPrice
      }
      return ''
    }
  },
  created() {
    this.getList()
    this.getShopOptions()
    this.getProductOptions()
  },
  methods: {
    /** 查询采购记录列表 */
    getList() {
      this.loading = true
      listPurchase(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.purchaseList = response.rows
        this.total = response.total
        this.loading = false
        
        // 从后端获取统计数据（基于查询条件，不受分页影响）
        if (response.statistics) {
          this.totalAmount = response.statistics.totalAmount ? '¥' + response.statistics.totalAmount.toFixed(2) : '¥0.00'
          this.totalQuantity = response.statistics.totalQuantity || 0
          this.totalRecords = response.statistics.totalRecords || 0
          this.avgUnitPrice = response.statistics.avgUnitPrice ? '¥' + response.statistics.avgUnitPrice.toFixed(2) : '¥0.00'
        } else {
          // 没有统计数据时的默认值
          this.totalAmount = '¥0.00'
          this.totalQuantity = 0
          this.totalRecords = 0
          this.avgUnitPrice = '¥0.00'
        }
      })
    },
    /** 获取店铺选项 */
    getShopOptions() {
      getShopList().then(response => {
        this.shopOptions = response.data
      })
    },
    /** 获取产品选项 */
    getProductOptions() {
      listProduct({ pageNum: 1, pageSize: 10000 }).then(response => {
        this.productOptions = response.rows
      })
    },
    /** SKU改变时自动填充产品名称和所属店铺 */
    handleSkuChange(sku) {
      const product = this.productOptions.find(p => p.sku === sku)
      if (product) {
        this.form.productName = product.productName
        this.form.shopId = product.shopId
        this.form.skuCode = product.skuCode
      }
    },
    /** 计算单价 */
    calculateUnitPrice() {
      // 使用computed属性自动计算，无需额外处理
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        inboundId: null,
        sku: null,
        productName: null,
        skuCode: null,
        shopId: null,
        purchaseQuantity: null,
        purchaseAmount: null,
        packageFee: 0,
        purchaseDate: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inboundId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加采购记录"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const inboundId = row.inboundId || this.ids
      getPurchase(inboundId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改采购记录"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.inboundId != null) {
            updatePurchase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPurchase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const inboundIds = row.inboundId || this.ids
      this.$modal.confirm('删除采购记录后将影响库存计算，是否确认删除？').then(function() {
        return delPurchase(inboundIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/purchase/export', {
        ...this.queryParams
      }, `purchase_manage_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "采购入库导入"
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('business/purchase/importTemplate', {
      }, `采购入库导入模板_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      
      if (response.code === 200) {
        this.$alert("<div style='overflow: auto; text-align: left;'>" + response.msg + "</div>", "导入结果", { 
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          callback: () => {
            this.getList()
          }
        })
      } else {
        this.$alert("<div style='overflow: auto; text-align: left;'>" + response.msg + "</div>", "导入失败", { 
          dangerouslyUseHTMLString: true,
          type: 'error'
        })
      }
    },
    // 文件上传失败处理
    handleFileError(err, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$modal.msgError("导入失败，请重试")
    },
    // 提交上传文件
    submitFileForm() {
      if (this.upload.isUploading) {
        this.$modal.msgWarning("正在导入中，请勿重复提交")
        return
      }
      this.$refs.upload.submit()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.purchase-records-section {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.stat-cards {
  margin-top: 20px;
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #fff;
  margin-right: 12px;
  flex-shrink: 0;
}

.stat-content {
  flex: 1;
  min-width: 0;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 3px;
  word-break: break-all;
}

.stat-label {
  font-size: 13px;
  color: #909399;
}
</style>

